package com.jsy.imagepicker;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;

public class ImagePickerActivity extends AppCompatActivity {
    static final int ACTION_TO_CAMERA = 1;
    static final int ACTION_TO_CUT = 2;
    static final int ACTION_TO_PREVIEW = 3;
    private Uri cropUri;

    ImageView ivBack;
    TextView tvConfirm;
    RecyclerView rv;
    View.OnClickListener onClickListener;
    Context mContext;
    PickerAdapter pickerAdapter;
    ImagePicker.Parameters parameters;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_image_picker);
        setNoTitle();
        getIntentData();
        findViewById();
        setAdapter();


    }

    @Override
    protected void onResume() {
        super.onResume();
        tvConfirm.setText(getString(R.string.complete) + "(" + PickerAdapter.checkedList.size() + "/" + parameters.mMaxCount + ")");
        pickerAdapter.notifyDataSetChanged();
    }

    private void getIntentData() {
        parameters = (ImagePicker.Parameters) getIntent().getSerializableExtra("parameters");
    }

    private void setNoTitle() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        try {
            getSupportActionBar().hide();
        } catch (Exception e) {
        }
    }

    private void setAdapter() {
        ((GridLayoutManager) rv.getLayoutManager()).setSpanCount(parameters.mSpanCount);
        int itemHeight = getWindowManager().getDefaultDisplay().getWidth() / parameters.mSpanCount;
        rv.setAdapter(pickerAdapter = new PickerAdapter(ImagePickerActivity.this, parameters, itemHeight) {
            @Override
            public void onImageChecked(int count, int checkedCount) {
                tvConfirm.setText(getString(R.string.complete) + "(" + checkedCount + "/" + count + ")");
                if (PickerAdapter.checkedList.size() == 0) {
                    tvConfirm.setBackgroundResource(R.drawable.bg_item_type);
                    tvConfirm.setTextColor(Color.parseColor("#808080"));
                } else {
                    tvConfirm.setBackgroundResource(R.drawable.bg_confirm);
                    tvConfirm.setTextColor(Color.parseColor("#f0f0f0"));
                }
            }

            @Override
            public void openCamera() {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                ContentValues contentValues = new ContentValues(1);
                contentValues.put(MediaStore.Images.Media.TITLE, System.currentTimeMillis() + ".jpg");
                Uri uri = mContext.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(intent, ACTION_TO_CAMERA);
            }
        });
    }

    private void findViewById() {
        ivBack = findViewById(R.id.iv_back);
        tvConfirm = findViewById(R.id.tv_confirm);
        tvConfirm.setText(getString(R.string.complete) + "(" + 0 + "/" + parameters.mMaxCount + ")");
        rv = findViewById(R.id.rv);
        onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getId() == R.id.iv_back) {
                    finish();
                } else if (v.getId() == R.id.tv_confirm) {
                    onConfirmClick();
                }
            }
        };
        ivBack.setOnClickListener(onClickListener);
        tvConfirm.setOnClickListener(onClickListener);
    }

    private void onConfirmClick() {
        if (parameters.mMaxCount == 1 && pickerAdapter.checkedList.size() == 1 && parameters.mCut) {
            toCut();
        } else {
            if (pickerAdapter.checkedList.size() > 0) {
                setResult(RESULT_OK, new Intent().putExtra("imagesList", pickerAdapter.checkedList));
                finish();
            }
        }
    }


    /**
     * 单选模式下的裁剪
     */
    void toCut() {
        cropUri = Uri.fromFile(new File(PickerUtils.getImagesDirPath(mContext), System.currentTimeMillis() + ".jpg"));
        Uri photoURI = PickerUtils.getImageContentUri(mContext, new File(pickerAdapter.checkedList.get(0)));
        Intent intent =
                new Intent("com.android.camera.action.CROP")
                        .setDataAndType(photoURI, "image/*")
                        .putExtra("crop", "true")
                        .putExtra(MediaStore.EXTRA_OUTPUT, cropUri)
                        .putExtra("aspectX", parameters.mAspectX)
                        .putExtra("aspectY", parameters.mAspectY)
                        .putExtra("outputFormat", Bitmap.CompressFormat.JPEG)
                        .putExtra("outputX", parameters.mCutWidth)
                        .putExtra("outputY", parameters.mCutHeight)
                        .putExtra("return-data", false)
                        .putExtra("scale", true)
                        .putExtra("scaleUpIfNeeded", true);
        startActivityForResult(intent, ACTION_TO_CUT);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case ACTION_TO_CAMERA:
                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(PickerUtils.getImagesDirPath(mContext)))));
                    pickerAdapter.refreshData();
                    break;
                case ACTION_TO_CUT:
                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(PickerUtils.getImagesDirPath(mContext)))));
                    ArrayList<String> list = new ArrayList<>();
                    list.add(cropUri.getPath());
                    setResult(RESULT_OK, new Intent().putExtra("imagesList", list));
                    finish();
                    break;
                case ACTION_TO_PREVIEW:
                    onConfirmClick();
                    break;
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        PickerAdapter.allList = null;
        PickerAdapter.checkedList = null;
    }
}
